'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';

interface Question {
  stem: string;         // 题干
  difficulty: number;   // 难度
  answer: any;          // 答案（可能是数字、数组等）
  hint1?: string;       // 提示1
  hint2?: string;       // 提示2
  solution: string;     // 解析
  knowledge?: string;   // 知识点
}

interface QuestionData {
  question: Question;
  questionId: string;
  topicId: string;
  topicName: string;
  questionIndex: number;
  stats: {
    total: number;
    reviewed: number;
    remaining: number;
    currentIndex: number;
  };
}

interface Stats {
  overall: {
    total: number;
    reviewed: number;
    correct: number;
    incorrect: number;
    marked: number;
    skipped: number;
    remaining: number;
    progress: string;
  };
  byTopic: Array<{
    topicId: string;
    topicName: string;
    total: number;
    reviewed: number;
    correct: number;
    marked: number;
    skipped: number;
  }>;
  problems: Array<any>;
}

export default function QuestionReviewPage() {
  const [currentQuestion, setCurrentQuestion] = useState<QuestionData | null>(null);
  const [stats, setStats] = useState<Stats | null>(null);
  const [mode, setMode] = useState<'all' | 'topic' | 'problem'>('all');
  const [selectedTopic, setSelectedTopic] = useState<string>('');
  const [userAnswer, setUserAnswer] = useState<string>('');
  const [showSolution, setShowSolution] = useState(false);
  const [loading, setLoading] = useState(false);
  const [showMarkDialog, setShowMarkDialog] = useState(false);
  const [markData, setMarkData] = useState({
    issueType: '',
    notes: ''
  });
  const [completed, setCompleted] = useState(false);

  // 加载统计数据
  const loadStats = async () => {
    try {
      const res = await fetch('/api/admin/question-review/stats');
      if (res.ok) {
        const data = await res.json();
        setStats(data);
      }
    } catch (error) {
      console.error('加载统计失败:', error);
    }
  };

  // 加载下一题
  const loadNextQuestion = async () => {
    setLoading(true);
    setUserAnswer('');
    setShowSolution(false);
    setCompleted(false);

    try {
      const params = new URLSearchParams({ mode });
      if (mode === 'topic' && selectedTopic) {
        params.append('topicId', selectedTopic);
      }

      const res = await fetch(`/api/admin/question-review/next?${params}`);
      const data = await res.json();

      if (!res.ok) {
        console.error('API错误:', data);
        alert(`加载失败: ${data.error || '未知错误'}`);
        return;
      }

      if (data.completed) {
        setCompleted(true);
        setCurrentQuestion(null);
      } else {
        console.log('加载的题目数据:', data);
        setCurrentQuestion(data);
      }
    } catch (error) {
      console.error('加载题目失败:', error);
      alert('加载题目失败，请检查网络连接');
    } finally {
      setLoading(false);
    }
  };

  // 标记题目
  const markQuestion = async (status: string, issueType?: string, notes?: string) => {
    if (!currentQuestion) return;

    try {
      const res = await fetch('/api/admin/question-review/mark', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          questionId: currentQuestion.questionId,
          topicId: currentQuestion.topicId,
          topicName: currentQuestion.topicName,
          questionIndex: currentQuestion.questionIndex,
          status,
          issueType,
          notes
        })
      });

      if (res.ok) {
        // 刷新统计
        await loadStats();
        // 重置解析显示状态
        setShowSolution(false);
        // 如果是答对、标记或跳过，自动加载下一题
        if (status === 'correct' || status === 'marked' || status === 'skipped') {
          await loadNextQuestion();
        }
      }
    } catch (error) {
      console.error('标记失败:', error);
    }
  };

  // 标记为有问题
  const handleMarkProblem = () => {
    setShowMarkDialog(true);
  };

  // 确认标记
  const confirmMark = async () => {
    await markQuestion('marked', markData.issueType, markData.notes);
    setShowMarkDialog(false);
    setMarkData({ issueType: '', notes: '' });
    // markQuestion已经会自动加载下一题，不需要重复调用
  };

  // 跳过
  const handleSkip = async () => {
    await markQuestion('skipped');
    // markQuestion已经会自动加载下一题，不需要重复调用
  };

  // 导出报告
  const handleExport = async () => {
    try {
      const res = await fetch('/api/admin/question-review/export');
      const blob = await res.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `question-review-report-${Date.now()}.md`;
      a.click();
    } catch (error) {
      console.error('导出失败:', error);
    }
  };

  useEffect(() => {
    loadStats();
    loadNextQuestion();
  }, [mode, selectedTopic]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 p-6">
      <div className="max-w-6xl mx-auto">
        {/* 标题 */}
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">📋 题库全量检测系统</h1>
          <p className="text-gray-600">系统化检测所有题目，确保题库质量</p>
        </div>

        {/* 统计面板 */}
        {stats && (
          <Card className="p-6 mb-6 bg-white shadow-lg">
            <h2 className="text-xl font-bold mb-4">📊 检测进度</h2>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
              <div className="text-center p-4 bg-blue-50 rounded-lg">
                <div className="text-3xl font-bold text-blue-600">{stats.overall.total}</div>
                <div className="text-sm text-gray-600">总题目数</div>
              </div>
              <div className="text-center p-4 bg-green-50 rounded-lg">
                <div className="text-3xl font-bold text-green-600">{stats.overall.correct}</div>
                <div className="text-sm text-gray-600">已检测正确</div>
              </div>
              <div className="text-center p-4 bg-red-50 rounded-lg">
                <div className="text-3xl font-bold text-red-600">{stats.overall.marked}</div>
                <div className="text-sm text-gray-600">发现问题</div>
              </div>
              <div className="text-center p-4 bg-purple-50 rounded-lg">
                <div className="text-3xl font-bold text-purple-600">{stats.overall.remaining}</div>
                <div className="text-sm text-gray-600">剩余未检测</div>
              </div>
            </div>
            <div className="mb-4">
              <div className="flex justify-between text-sm mb-1">
                <span>整体进度</span>
                <span>{stats.overall.progress}%</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-4">
                <div 
                  className="bg-gradient-to-r from-blue-500 to-purple-500 h-4 rounded-full transition-all"
                  style={{ width: `${stats.overall.progress}%` }}
                ></div>
              </div>
            </div>
            <div className="flex gap-2">
              <Button onClick={handleExport} variant="outline">
                📥 导出问题报告
              </Button>
            </div>
          </Card>
        )}

        {/* 检测模式切换 */}
        <Card className="p-4 mb-6 bg-white shadow-lg">
          <div className="flex gap-4 items-center">
            <span className="font-semibold">检测模式:</span>
            <Button 
              onClick={() => setMode('all')}
              variant={mode === 'all' ? 'default' : 'outline'}
            >
              全部检测
            </Button>
            <Button 
              onClick={() => setMode('problem')}
              variant={mode === 'problem' ? 'default' : 'outline'}
            >
              问题复查
            </Button>
          </div>
        </Card>

        {/* 题目显示 */}
        {loading && (
          <Card className="p-8 text-center bg-white shadow-lg">
            <div className="text-gray-600">加载中...</div>
          </Card>
        )}

        {completed && (
          <Card className="p-8 text-center bg-white shadow-lg">
            <div className="text-4xl mb-4">🎉</div>
            <h2 className="text-2xl font-bold text-gray-800 mb-2">检测完成！</h2>
            <p className="text-gray-600">所有题目已检测完毕</p>
          </Card>
        )}

        {!loading && !completed && currentQuestion && (
          <Card className="p-6 bg-white shadow-lg">
            {/* 题目信息 */}
            <div className="mb-4 pb-4 border-b">
              <div className="flex justify-between items-center">
                <div>
                  <span className="text-sm text-gray-500">
                    进度: {currentQuestion.stats?.currentIndex || 0} / {currentQuestion.stats?.total || 0}
                  </span>
                  <div className="text-sm text-gray-600 mt-1">
                    <span className="font-semibold">{currentQuestion.topicName}</span>
                    <span className="mx-2">•</span>
                    <span>难度: {'⭐'.repeat(currentQuestion.question?.difficulty || 1)}</span>
                  </div>
                </div>
                <div className="text-sm text-gray-500">
                  剩余: {currentQuestion.stats?.remaining || 0} 题
                </div>
              </div>
            </div>

            {/* 题目内容 */}
            <div className="mb-6">
              <h3 className="text-lg font-semibold mb-4 text-gray-800">
                {currentQuestion.question?.stem || '题目加载中...'}
              </h3>
              
              {/* 提示信息 */}
              {currentQuestion.question?.hint1 && !showSolution && (
                <div className="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="text-sm text-blue-700">
                    <strong>💡 提示1:</strong> {currentQuestion.question.hint1}
                  </div>
                  {currentQuestion.question?.hint2 && (
                    <div className="text-sm text-blue-700 mt-2">
                      <strong>💡 提示2:</strong> {currentQuestion.question.hint2}
                    </div>
                  )}
                </div>
              )}
              
              {/* 答案和解析显示区 */}
              <div className="mb-6 p-4 bg-blue-50 border border-blue-300 rounded-lg">
                <div className="flex items-center justify-between mb-3">
                  <div className="font-semibold text-lg text-blue-900">
                    ✅ 标准答案: <span className="text-green-600">{JSON.stringify(currentQuestion.question?.answer)}</span>
                  </div>
                  <button
                    onClick={() => setShowSolution(!showSolution)}
                    className="text-sm px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600"
                  >
                    {showSolution ? '隐藏解析' : '查看解析'}
                  </button>
                </div>
                
                {showSolution && currentQuestion.question?.solution && (
                  <div className="mt-3 p-3 bg-white rounded border border-blue-200">
                    <div className="text-sm text-gray-700 whitespace-pre-wrap">
                      <strong className="text-blue-700">📝 解析过程:</strong><br/>
                      <div className="mt-2">{currentQuestion.question.solution}</div>
                    </div>
                  </div>
                )}
              </div>
            </div>

            {/* 检测说明 */}
            <div className="mb-4 p-3 bg-gray-50 border border-gray-300 rounded-lg">
              <div className="text-sm text-gray-700">
                <strong>💡 检测说明：</strong>请检查上方的答案和解析是否正确、清晰。如有问题请标记。
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-3 flex-wrap">
              <Button 
                onClick={() => markQuestion('correct')}
                className="bg-green-500 hover:bg-green-600 text-white"
              >
                ✅ 答案正确，下一题
              </Button>
              <Button 
                onClick={handleMarkProblem} 
                className="bg-red-500 hover:bg-red-600 text-white"
              >
                ❌ 标记问题
              </Button>
              <Button 
                onClick={handleSkip} 
                variant="outline"
                className="border-gray-400"
              >
                ⏭️ 跳过此题
              </Button>
            </div>
          </Card>
        )}

        {/* 标记对话框 */}
        {showMarkDialog && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <Card className="p-6 max-w-md w-full mx-4 bg-white">
              <h3 className="text-xl font-bold mb-4">🚩 标记问题题目</h3>
              <div className="mb-4">
                <label className="block text-sm font-semibold mb-2">问题类型</label>
                <select 
                  className="w-full p-2 border rounded-lg"
                  value={markData.issueType}
                  onChange={(e) => setMarkData({...markData, issueType: e.target.value})}
                >
                  <option value="">请选择</option>
                  <option value="answer_wrong">答案错误</option>
                  <option value="solution_unclear">解析不清</option>
                  <option value="question_wrong">题目错误</option>
                  <option value="other">其他问题</option>
                </select>
              </div>
              <div className="mb-4">
                <label className="block text-sm font-semibold mb-2">备注</label>
                <textarea 
                  className="w-full p-2 border rounded-lg"
                  rows={3}
                  value={markData.notes}
                  onChange={(e) => setMarkData({...markData, notes: e.target.value})}
                  placeholder="请描述具体问题..."
                />
              </div>
              <div className="flex gap-3">
                <Button onClick={confirmMark}>确认标记</Button>
                <Button onClick={() => setShowMarkDialog(false)} variant="outline">取消</Button>
              </div>
            </Card>
          </div>
        )}
      </div>
    </div>
  );
}

